﻿using CorsOption = MicroCloud.Options.CorsOption;

namespace MicroCloud.AspNetCore.Cors
{
    /// <summary>
    /// 默认Cors跨源资源共享服务初始化器
    /// </summary>
    public class DefaultCorsInitializer : ICorsInitializer
    {
        /// <summary>
        /// 获取 Cors跨域策略选项
        /// </summary>
        public CorsOption CorsOptions { get; private set; }

        /// <summary>
        /// 添加Cors跨源资源共享服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns></returns>
        public virtual IServiceCollection AddCors(IServiceCollection services)
        {
            CorsOptions = services.GetMicroCloudOptions().Cors;
            //CorsOptions.Enabled = configuration["MicroCloud:Cors:Enabled"].CastTo(false);
            CorsOptions.PolicyName = CorsOptions.PolicyName.IsMissing() ? SettingKeyConstants.CoresName : CorsOptions.PolicyName;
            if (!CorsOptions.Enabled)
            {
                return services;
            }
            services.AddCors(opts => opts.AddPolicy(CorsOptions.PolicyName,
                policy =>
                {
                    //设置请求头
                    if (CorsOptions.AllowAnyHeader) { policy.AllowAnyHeader(); }
                    else if (CorsOptions.WithHeaders != null) { policy.WithHeaders(CorsOptions.WithHeaders); }
                    //设置请求方法
                    if (CorsOptions.AllowAnyMethod) { policy.AllowAnyMethod(); }
                    else if (CorsOptions.WithMethods != null) { policy.WithMethods(CorsOptions.WithMethods); }
                    //设置 允许跨域凭据、禁止跨域凭据
                    if (CorsOptions.AllowCredentials) { policy.AllowCredentials(); }
                    else if (CorsOptions.DisallowCredentials) { policy.DisallowCredentials(); }
                    //设置站点跨域请求（请求来源）
                    if (CorsOptions.AllowAnyOrigin)
                    {
                        //policy.AllowAnyOrigin();  //允许所有站点跨域请求（net core2.2版本后将不适用）
                        policy.SetIsOriginAllowed(_ => true);  //允许所有站点跨域请求
                    }
                    else if (CorsOptions.WithOrigins != null) { policy.WithOrigins(CorsOptions.WithOrigins); }
                }));

            return services;
        }

        /// <summary>
        /// 应用Cors跨源资源共享服务
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public virtual IApplicationBuilder UseCors(IApplicationBuilder app)
        {
            if (CorsOptions.Enabled)
            {
                app.UseCors(CorsOptions.PolicyName);
            }
            return app;
        }

    }
}